package com.blockchainenergy.common.memory;

import com.blockchainenergy.common.memory.info.ElecMeterInfo;
import com.blockchainenergy.common.memory.log.UserMeterLog;
import com.blockchainenergy.common.memory.log.UserWalletLog;
import com.blockchainenergy.mqtt.server.MqttParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Memory {
    public final static HashMap<String, UserWalletLog> userWalletLogMap = new HashMap<>();// userid ,value
    public final static HashMap<String, UserMeterLog> userMeterLogMap = new HashMap<>();// meterId ,value

    public static UserMeterLog getMeterLog(String meterId) {
        return userMeterLogMap.get(meterId);
    }

    public static UserWalletLog getWalletLog(String userId) {
        if (!userWalletLogMap.containsKey(userId)) userWalletLogMap.put(userId, new UserWalletLog());
        return userWalletLogMap.get(userId);
    }

    public static boolean addMeter(String userId) {
        if (userMeterLogMap.containsKey(userId)) return false;
        userMeterLogMap.put(userId, new UserMeterLog());
        return true;
    }

    public static void addMeterLog(MqttParam mqttParam) {
        String elec_meter_id = mqttParam.getElec_meter_id();
        UserMeterLog userMeterLog = userMeterLogMap.get(elec_meter_id);
        if (userMeterLog == null) return;

        Double v = mqttParam.getV();
        Double a = mqttParam.getA();
        Double pia = mqttParam.getPIA();
        Double pir = mqttParam.getPIR();
        userMeterLog.add(v, a, pia, pir);
    }

    public static void addWalletLog(String userId, double balance, double credit_point) {
        if (!userWalletLogMap.containsKey(userId)) userWalletLogMap.put(userId, new UserWalletLog());
        userWalletLogMap.get(userId).add(balance, credit_point);
    }

    public static List<ElecMeterInfo> getAllElecMeter() {
        List<ElecMeterInfo> list = new ArrayList<>();
        for (Map.Entry<String, UserMeterLog> meterEntry : userMeterLogMap.entrySet()) {
            list.add(new ElecMeterInfo(meterEntry));
        }
        return list;
    }
}
